/**
 * Notes: 资讯后台管理模块业务逻辑
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2020-11-14 07:48:00 
 */

// 导入路径解析器
const pathResolver = require('../../config/path_resolver.js');

// 导入服务层配置辅助模块 - 使用统一配置入口模式
const serviceHelper = require('../../config/service_helper_config.js');
const { projectSetting, cloudHelper, timeHelper, dataHelper, util, BaseBiz } = serviceHelper;

// 正常导入本目录下的NewsService
const NewsService = require('../news/news_service.js');

// 使用统一入口导入的projectSetting
let _projectSetting = projectSetting;

/**
 * 资讯后台管理服务类
 */
class AdminNewsService extends BaseBiz {

	/** 表单初始化相关数据 */
	static initFormData(id = '') {
		let cateIdOptions = AdminNewsService.getCateList();

		return {
			id,

			contentDesc: '',

			// 分类
			cateIdOptions,

			fields: _projectSetting.NEWS_FIELDS,

			// 图片数据 
			imgList: [],


			// 表单数据  
			formOrder: 9999,
			formTitle: '',
			formDesc: '',
			formContent: [],
			formCateId: (cateIdOptions.length == 1) ? cateIdOptions[0].val : '',
			formForms:[],
		}

	}

	static getCateName(cateId) {
		let cateList = _projectSetting.NEWS_CATE;

		for (let k = 0; k < cateList.length; k++) {
			if (cateList[k].id == cateId) return cateList[k].title;
		}
		return '';
	}

	/**
	 * 获取新闻分类列表
	 * 从项目配置中读取
	 */
	static getCateList() {
		// 尝试从项目设置读取
		let cateList = _projectSetting.NEWS_CATE;
		
		// 如果未定义，提供默认值
		if (!cateList || !Array.isArray(cateList)) {
			return [{
				label: '默认分类',
				val: 'default',
				id: 'default',
				title: '默认分类'
			}];
		}
		
		// 格式化分类数据为标准格式
		return cateList.map(item => {
			return {
				label: item.title,
				val: item.id,
				id: item.id,
				title: item.title
			};
		});
	}

	/**
	 * 获取新闻分页列表
	 */
	static async getNewsList({
		search,
		sortType,
		sortVal,
		orderBy,
		whereEx,
		page,
		size,
		isTotal = true,
		oldTotal
	}) {

		orderBy = orderBy || {
			'NEWS_ORDER': 'asc',
			'NEWS_ADD_TIME': 'desc'
		};

		let fields = '*';

		let where = {};
		if (util.isDefined(search) && search) {
			where.NEWS_TITLE = {
				$regex: '.*' + search,
				$options: 'i'
			};
		}

		return await cloudHelper.callCloudData('admin/news_list', {
			search,
			sortType,
			sortVal,
			orderBy,
			whereEx,
			page,
			size,
			isTotal,
			oldTotal,
			where,
			fields
		});
	}

	/**
	 * 获取新闻详情
	 * @param {*} id 
	 */
	static async getNewsDetail(id) {
		let fields = '*';

		let where = {
			_id: id
		}
		let news = await cloudHelper.callCloudData('admin/news_detail', {
			where,
			fields
		});
		if (!news) return null;

		return news;
	}

	/**
	 * 新闻表单校验
	 * @param {*} data 
	 * @param {*} oldDetail 
	 */
	static validateNewsForm(data, oldDetail) {
		// 标题
		if (!data.title)
			return '请填写新闻标题';

		if (data.title.length > 100)
			return '新闻标题不能超过100个字符';

		// 排序
		if (!data.order)
			return '请填写排序号';

		if (!Number.isInteger(Number(data.order)))
			return '排序号必须为整数';

		// 内容
		if (!data.content)
			return '请填写新闻内容';

		if (data.content.length > 50000)
			return '新闻内容不能超过50000个字符';

		return '';
	}

	/**
	 * 添加新闻
	 * @param {*} adminId 
	 * @param {*} data 
	 */
	static async insertNews(adminId, data) {
		// 表单校验
		let check = AdminNewsService.validateNewsForm(data);
		if (check) return {
			code: -1,
			msg: check
		};

		// 构建数据
		let newsData = {};
		newsData.NEWS_TITLE = data.title;
		newsData.NEWS_CONTENT = data.content;
		newsData.NEWS_CATE = data.cate;
		newsData.NEWS_ORDER = Number(data.order);
		newsData.NEWS_STATUS = Number(data.status);
		newsData.NEWS_COVER = data.cover;
		newsData.NEWS_ADMIN_ID = adminId;
		newsData.NEWS_ADD_TIME = timeHelper.time();
		newsData.NEWS_EDIT_TIME = timeHelper.time();
		newsData.NEWS_EDIT_IP = util.getIP();

		return await cloudHelper.callCloudSumbit('admin/news_insert', newsData);
	}

	/**
	 * 更新新闻
	 * @param {*} id 
	 * @param {*} adminId 
	 * @param {*} data 
	 */
	static async editNews(id, adminId, data) {
		// 表单校验
		let check = AdminNewsService.validateNewsForm(data);
		if (check) return {
			code: -1,
			msg: check
		};

		// 获取旧数据
		let oldDetail = await AdminNewsService.getNewsDetail(id);
		if (!oldDetail) return {
			code: -1,
			msg: '该新闻不存在'
		};

		// 构建数据
		let newsData = {};
		newsData.NEWS_TITLE = data.title;
		newsData.NEWS_CONTENT = data.content;
		newsData.NEWS_CATE = data.cate;
		newsData.NEWS_ORDER = Number(data.order);
		newsData.NEWS_STATUS = Number(data.status);
		newsData.NEWS_COVER = data.cover;
		newsData.NEWS_ADMIN_ID = adminId;
		newsData.NEWS_EDIT_TIME = timeHelper.time();
		newsData.NEWS_EDIT_IP = util.getIP();

		return await cloudHelper.callCloudSumbit('admin/news_edit', {
			id,
			data: newsData
		});
	}

	/**
	 * 更新新闻状态
	 * @param {String} id 新闻ID
	 * @param {Number} status 状态
	 */
	static async updateNewsStatus(id, status) {
		if (!id) return { code: -1, msg: '操作ID不能为空' };
		
		try {
			let params = { id, status };
			return await cloudHelper.callCloudSumbit('admin/news_status', params);
		} catch (error) {
			console.error('更新新闻状态失败', error);
			return { code: -1, msg: '更新失败：' + error.message };
		}
	}

	/**
	 * 更新新闻排序
	 * @param {String} id 新闻ID
	 * @param {Number} sort 排序号
	 */
	static async updateNewsSort(id, sort) {
		if (!id) return { code: -1, msg: '操作ID不能为空' };
		
		try {
			let params = { id, sort };
			return await cloudHelper.callCloudSumbit('admin/news_sort', params);
		} catch (error) {
			console.error('更新新闻排序失败', error);
			return { code: -1, msg: '更新失败：' + error.message };
		}
	}

	/**
	 * 更新新闻推荐状态
	 * @param {String} id 新闻ID
	 * @param {Number} vouch 推荐状态
	 */
	static async updateNewsVouch(id, vouch) {
		if (!id) return { code: -1, msg: '操作ID不能为空' };
		
		try {
			let params = { id, vouch };
			return await cloudHelper.callCloudSumbit('admin/news_vouch', params);
		} catch (error) {
			console.error('更新新闻推荐状态失败', error);
			return { code: -1, msg: '更新失败：' + error.message };
		}
	}

	/**
	 * 删除新闻
	 * @param {String} id 新闻ID
	 */
	static async deleteNews(id) {
		if (!id) return { code: -1, msg: '操作ID不能为空' };
		
		try {
			let params = { id };
			return await cloudHelper.callCloudSumbit('admin/news_del', params, { title: '删除中' });
		} catch (error) {
			console.error('删除新闻失败', error);
			return { code: -1, msg: '删除失败：' + error.message };
		}
	}
}

/** 表单校验  本地 */
AdminNewsService.CHECK_FORM = {
	title: 'formTitle|must|string|min:4|max:50|name=标题',
	cateId: 'formCateId|must|id|name=分类',
	order: 'formOrder|must|int|min:0|max:9999|name=排序号',
	desc: 'formDesc|string|min:10|max:200|name=简介',
	forms: 'formForms|array',
};

module.exports = AdminNewsService;